package command.server;

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import model.Message;
import model.MessageCommunication;
import server.ClientThread;
import server.Server;

public class SendMessageServer implements CommandServer {

    private String conversationID;
    private Message messageToAdd;
    private boolean isSendMessage = false;

    public SendMessageServer() {
    }

    public void setConversationID(String idOfConversation) {
        conversationID = idOfConversation;
    }

    public void setMessageToAdd(Message message) {
        messageToAdd = message;
    }

    public void setIsSendMessage() {
        isSendMessage = true;
    }

    @Override
    public void execute(ClientThread clientThread) {
        try {
            if (!isSendMessage) {
                MessageCommunication conversation = (MessageCommunication) clientThread.getObjectInputStream().
                        readObject();
                Message newMessage = (Message) clientThread.getObjectInputStream().readObject();
                Server.addMessageAtConversation(conversation.getMessage(), newMessage);
            } else {
                clientThread.getObjectOutputStream().writeObject(
                        new MessageCommunication(true, "sendmessageclient"));
                clientThread.getObjectOutputStream().flush();
                clientThread.getObjectOutputStream().writeObject(new MessageCommunication(true, conversationID));
                clientThread.getObjectOutputStream().flush();
                clientThread.getObjectOutputStream().writeObject(messageToAdd);
                clientThread.getObjectOutputStream().flush();
            }
        } catch (IOException | ClassNotFoundException ex) {
            Logger.getLogger(SendMessageServer.class.getName()).log(Level.SEVERE,
                    "Fallo al realizar el envío de un mensaje de la conversación a los clientes", ex);
        }
    }
}
